#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <papi.h>

void do_something (void)
{
	unsigned long long value;
	int i;

	for (i = value = 0; i < 100000; i++)
		value += i >> 2;

	fprintf (stdout, "do_something value = %llu\n", value);
}

int main (int argc, char *argv[])
{
	int e = PAPI_NULL;
	unsigned long long values[16];
  int rc;

#if defined(DEBUG)
	fprintf (stderr, "About to run PAPI_library_init\n");
#endif
  rc = PAPI_library_init (PAPI_VER_CURRENT);
  if (rc != PAPI_VER_CURRENT)
  {
    if (rc > 0)
    {
      fprintf (stderr,
        "mpitrace: PAPI library version mismatch!\n"
        "          MPItrace is compiled against PAPI v%d.%d , and \n"
        "          PAPI_library_init reported v%d.%d ,\n"
        "          Check that LD_LIBRARY_PATH points to the correct PAPI library.\n",
        PAPI_VERSION_MAJOR(PAPI_VER_CURRENT),
        PAPI_VERSION_MINOR(PAPI_VER_CURRENT),
        PAPI_VERSION_MAJOR(rc),
        PAPI_VERSION_MINOR(rc));
    }
    fprintf (stderr, "mpitrace: Can't use hardware counters!\n");
    fprintf (stderr, "mpitrace: PAPI library error: %s\n", PAPI_strerror (rc));

    if (rc == PAPI_ESYS)
      perror (" mpitrace: PAPI system error is ");

    return 0;
  }

#if defined(DEBUG)
	fprintf (stderr, "About to run PAPI_create_eventset\n");
#endif
	if (PAPI_create_eventset (&e) != PAPI_OK)
	{
		fprintf (stderr, "Failed to create event set\n");
		perror ("perror:");
		return 0;
	}

#if defined(DEBUG)
	fprintf (stderr, "About to run PAPI_add_event\n");
#endif
	if (PAPI_add_event(e, PAPI_TOT_CYC) != PAPI_OK)
	{
		fprintf (stderr, "Failed to add event\n");
		perror ("perror:");
		return 0;
	}

#if defined(DEBUG)
	fprintf (stderr, "About to run PAPI_start\n");
#endif
	if (PAPI_start (e) != PAPI_OK)
	{
		fprintf (stderr, "Failed to PAPI_start\n");
		perror ("perror:");
		return 0;
	}

	do_something();

#if defined(DEBUG)
	fprintf (stderr, "About to run PAPI_read\n");
#endif
	PAPI_read (e, values);

	fprintf (stdout, "PMC counter returned: %llu\n", values[0]);

	return 0;
}
